package com.example.sxproject.controller;

import com.example.sxproject.pojo.*;
import com.example.sxproject.service.CardService;
import com.example.sxproject.service.FinancialService;
import com.example.sxproject.service.PaymentService;
import jakarta.servlet.http.HttpSession;
import jakarta.validation.constraints.Pattern;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.h2.H2ConsoleAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/financial")
@Validated
public class FinancialController {

    @Autowired
    private FinancialService financialService;

    @Autowired
    private CardService cardService;

    @Autowired
    private PaymentService paymentService;

    //查询select：查询全部(包括假删除后)
    @PostMapping("/product")
    public Result getAllProducts() {
        List<FinancialProduct> products = financialService.SelectAll();
        return Result.success(products);
    }

    //查询select：根据用户id查询
    @PostMapping("/productByUserId")
    public Result getProductsByUserId(Integer userId) {
        List<FinancialProduct> products = financialService.SelectByUserId(userId);
        return Result.success(products);
    }

    //查询select：根据筛选条件查询
    @GetMapping("/productSearch")
    public String getProductsByStatus(FPSearch fpSearch, HttpSession session) {

        List<FinancialProduct> products = financialService.SelectFPSearch(fpSearch);
        session.setAttribute("financialProducts", products);

        return "financeProduct";
    }

    //添加insert：新增一个产品
    @PostMapping("/insertProduct")
    public Result addFinancialProduct(@RequestBody FinancialProduct financialProduct) {
        financialService.addFinancialProduct(financialProduct);
        return Result.success();
    }

    //添加insert：添加一个用户-产品
    @PostMapping("/insertUP")
    public Result addUserAndProduct(@RequestBody FinancialUser financialUser) {
        financialService.addUserAndProduct(financialUser);
        return Result.success();
    }

    //更新update：更新产品信息
    @PutMapping("/update")
    public Result update(@RequestBody @Validated FinancialProduct financialProduct) {
        financialService.update(financialProduct);
        return Result.success();
    }

    //更新update：更新用户-产品
    @PutMapping("/updateUP")
    public Result updateUP(@RequestBody @Validated FinancialUser financialUser) {
        financialService.updateUP(financialUser);
        return Result.success();
    }

    //更新update：实现假删除
    @PutMapping("/delete")
    public Result delete(@RequestBody @Validated FinancialProduct financialProduct) {
        financialProduct.setProductStatus(2);
        financialService.delete(financialProduct);
        return Result.success();
    }

    @GetMapping("/test")
    public Result Test123123(@Pattern(regexp = "^\\S{5,16}$") String username) {

        List<FinancialProduct> products = financialService.SelectAll();

        System.out.println("Your log message");

        return Result.success(products);
    }

    //理财产品支付功能
    @RequestMapping("/pay")
    public String addPayment(PayMessage payMessage, HttpSession session, Integer productId) {

        User user = (User) session.getAttribute("user");

        System.out.println(payMessage.getCardId());
        System.out.println(payMessage.getRecardId());

        //验证银行卡密码
        if (!cardService.verifyPassword(payMessage.getCardId(), payMessage.getPassword())) {
            session.setAttribute("msg", "密码错误");
            return "financeProduct";
        }

        //查找2个卡的信息
        Card card1 = cardService.findByIdNumber(payMessage.getCardId());//根据卡号找记录1:支付卡
        Card card2 = cardService.findByIdNumber(payMessage.getRecardId());//根据卡号找记录2：接收卡

        System.out.println(card2);

        double money = payMessage.getMoney();//转账金额

        //余额验证
        if(card1.getBalance() < money) {
            session.setAttribute("msg", "余额不足");
            return "financeProduct";
        }

        //更新银行卡余额，实现转钱
        cardService.updateBalance(card1.getIdNumber(), card1.getBalance() - money);// 进行转钱操作
        cardService.updateBalance(card2.getIdNumber(), card2.getBalance() + money);


        //传进来的参数要包括 支付卡号、接收卡号、金额、支付类型
        Payment payment = new Payment();  //第一个交易记录
        Payment payment1 = new Payment(); // 第二个交易记录

        //流水号
        UUID uuid1 = UUID.randomUUID(); // 使用uuid生成随机32位
        UUID uuid2 = UUID.randomUUID();

        payment.setIdNumber(String.valueOf(uuid1));
        payment1.setIdNumber(String.valueOf(uuid2));

        //支付方 和 接收方
        payment.setCardId(payMessage.getCardId()); // 第一个记录的支付方 接收方
        payment.setRecardId(payMessage.getRecardId());
        payment1.setCardId(payment.getRecardId()); // 第二个 交换支付方和接收方
        payment1.setRecardId(payment.getCardId());

        //支付时间，获取当前时间，转为string类型
        String time = LocalDateTime.now().toString();
        time = time.substring(0, 19);
        time = time.replace('T', ' ');
        payment.setPayDate(time);
        payment1.setPayDate(payment.getPayDate());

        //支付金额
        payment.setMoney(payMessage.getMoney());
        payment1.setMoney(payMessage.getMoney());

        // 更改支付类型 1转入 2转出
        payment.setTransType(2);
        payment1.setTransType(1);

        //支付类型 1 转账
        payment.setPayType(1);
        payment1.setPayType(1);

        //更新所属用户
        payment.setUserId(card1.getUserId());
        payment1.setUserId(card2.getUserId());

        //当前记录状态
        payment.setPaymentStatus(1);
        payment1.setPaymentStatus(1);

        //添加支付记录
        paymentService.addPayment(payment);
        paymentService.addPayment(payment1);

        //添加用户-产品表
        FinancialUser financialUser = new FinancialUser();
        financialUser.setBelongUser(user.getId());
        financialUser.setBelongProduct(productId);
        financialUser.setBalance(String.valueOf(money));
        financialUser.setProductStatus(1);
        financialUser.setProductName(payMessage.getRecName());
        financialService.addUserAndProduct(financialUser);

        session.setAttribute("msg", "");
        return "success";

    }


}
